<template>
	<view>
		<HeaderNavTabarVue title="轨迹记录" />
		<map id="myMap" style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="markers"
			:polyline="polyline" show-location></map>
		<view>总里程: {{ totalDistance }} 米</view>
		<view class="" v-for="(item,index) in polyline[0].points" :key="index">
			<view class="">
				{{item.latitude}} {{item.longitude}}
			</view>
		</view>
		<button @click="startTracking">开始记录</button>
		<button @click="stopTracking">停止记录</button>
		<button @click="toPage">换页面</button>
	</view>
</template>

<script setup>
	import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
	import locationWatcher from '@/utils/location.js'
	// #ifdef APP-PLUS
	import {
		startForegroundService,
		stopForegroundService
	} from "@/uni_modules/hr-persist-track"
	//  #endif

	import {
		onLoad,
		onShow,
		onHide,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		defineProps,
		nextTick,
		onMounted,
		ref
	} from 'vue'
	import store from '@/store/index'

	const latitude = ref('') // 初始纬度
	const longitude = ref('') // 初始经度
	const markers = ref([]) // 标记点
	const polyline = ref([{
		points: [], // 轨迹点数组
		color: '#00FF00', // 轨迹线颜色
		width: 5, // 轨迹线宽度
		dottedLine: false // 是否为虚线
	}])
	const trackPoints = ref([]) // 记录轨迹点
	const timer = ref(null) // 定时器
	const startPosition = ref(null) // 开始位置
	const totalDistance = ref(0) // 总里程
	const locationWatcherId = ref(null) // 步骤生成的监听器id

	onShow(() => {
	})

	onLoad(() => {
		// 监听应用进入后台（熄屏）
		// uni.onAppHide(() => {
		// 	console.log('App is in background (screen off)');
		// });

		// // 监听应用回到前台
		// uni.onAppShow(() => {
		// 	console.log('App is in foreground (screen on)');
		// 	// this.stopBackgroundLocation();
		// });

		if (store._state.data.gps.latitude) {
			latitude.value = store._state.data.gps.latitude
			longitude.value = store._state.data.gps.longitude
			markers.value = store._state.data.gps.markers
			polyline.value = store._state.data.gps.polyline
			totalDistance.value = store._state.data.gps.totalDistance
			locationWatcherId.value = store._state.data.gps.locationWatcherId
			updateMap()
		} else {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					latitude.value = res.latitude,
						longitude.value = res.longitude
					markers.value = [{
						latitude: res.latitude,
						longitude: res.longitude,
						iconPath: '../../static/logo.png', //地图上的图标
						width: 40, //宽
						height: 40, //高
					}]
				},
				fail: (err) => {
					console.error('获取位置失败', err);
				}
			});
		}
	})
	
	// 开始记录轨迹
	const startTracking = () => {
		console.log('开始记录轨迹')
		// #ifdef APP-PLUS
		startForegroundService()
		// #endif
		locationWatcher.startLocationService(e => {
			console.log('定位中', e)

			if (!locationWatcherId.value) {
				locationWatcherId.value = e.locationWatcherId //举例保存到data，实际可以缓存到全局
				store._mutations.setLocationWatcherId[0](locationWatcherId.value)
			}
			const point = {
				latitude: e.position.latitude,
				longitude: e.position.longitude
			};
			// 记录轨迹点
			trackPoints.value.push(point);

			// 记录里程
			if (startPosition.value) {
				const distance = calculateDistance(startPosition.value, point);
				totalDistance.value += distance;
				console.log(`当前里程: ${totalDistance.value.toFixed(2)} 米`);
			}
			startPosition.value = point;

			updateMap(); // 更新地图
		}, (e) => {
			console.log(e, '定位失败')
		}, 10 * 1000)
	}

	const calculateDistance = (pos1, pos2) => {
		const R = 6371000; // 地球半径，单位米
		const dLat = (pos2.latitude - pos1.latitude) * Math.PI / 180;
		const dLon = (pos2.longitude - pos1.longitude) * Math.PI / 180;
		const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
			Math.cos(pos1.latitude * Math.PI / 180) * Math.cos(pos2.latitude * Math.PI / 180) *
			Math.sin(dLon / 2) * Math.sin(dLon / 2);
		const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		return R * c;
	}

	// 停止记录轨迹
	const stopTracking = () => {
		clearInterval(timer.value);
		console.log('轨迹记录已停止');
		console.log(`总里程: ${totalDistance.value.toFixed(2)} 米`);
		// #ifdef APP-PLUS
		locationWatcher.closeLocationService(locationWatcherId.value);
		stopForegroundService()
		//  #endif
		// #ifndef APP-PLUS
		uni.offLocationChange()
		//  #endif
		locationWatcherId.value = null
		store._mutations.setLocationWatcherId[0](null)
		store._mutations.setLatitude[0]('')
		store._mutations.setLongitude[0]('')
		store._mutations.setMarkers[0]([])
		store._mutations.setPolyline[0]([])
		store._mutations.setTotalDistance[0]('')
	}

	// 更新地图显示
	const updateMap = () => {
		if (trackPoints.value.length > 0) {
			const lastPoint = trackPoints.value[trackPoints.value.length - 1];
			latitude.value = lastPoint.latitude;
			longitude.value = lastPoint.longitude;

			// 更新标记点
			markers.value = [{
				id: 1,
				latitude: lastPoint.latitude,
				longitude: lastPoint.longitude,
				iconPath: '../../static/logo.png', //地图上的图标
				width: 40, //宽
				height: 40, //高
			}];

			// 更新轨迹线
			polyline.value = [{
				points: trackPoints.value,
				color: '#00FF00',
				width: 5,
				dottedLine: false
			}];

			store._mutations.setLatitude[0](latitude.value)
			store._mutations.setLongitude[0](longitude.value)
			store._mutations.setMarkers[0](markers.value)
			store._mutations.setPolyline[0](polyline.value)
			store._mutations.setTotalDistance[0](totalDistance.value)
		}
	}

	const toPage = () => {
		uni.navigateTo({
			url: '/pages/visit/gps'
		})
	}
</script>
<style scoped lang="scss">

</style>